package com.bee.剑指offer;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 请从字符串中找出一个最长的不包含重复字符的子字符串，计算该最长子字符串的长度。
 * 输入："abcabcbb"
 * 返回值：3
 * 说明：因为无重复字符的最长子串是"abc"，所以其长度为 3。
 */
public class 最长不含重复字符的子字符串 {

    public static int lengthOfLongestSubstring(String s) {
        // 这里必须要用set，使用List会报错
        Set<Character> characters = new LinkedHashSet<>();
        int high = 0;
        int low = 0;
        int count = 0;
        while (high < s.length()) {
            while (characters.contains(s.charAt(high))) {
                System.out.println(characters.toString());
                characters.remove(s.charAt(low++));
            }
            characters.add(s.charAt(high++));
            count = Math.max(count, high - low);
        }
        return count;
    }

    public static int lengthOf(String s) {
        if (s == null || s.length() <= 0) {
            return 0;
        }
        Set<Character> set = new LinkedHashSet<>();
        int low = 0;
        int high = 0;
        int count = 0;
        while (high < s.length()) {
            while (set.contains(s.charAt(low))) {
                set.remove(s.charAt(low++));
            }
            set.add(s.charAt(high++));
            count = Math.max(count, high - low);
        }
        return count;
    }


    public static void main(String[] args) {
        int count = lengthOfLongestSubstring("abcabcbb");
        System.out.println(count);
    }
}
